package com.qs.javame.thread.state;

import com.qs.javame.thread.utils.SleepUtils;

public class ThreadState {


    /**
     * 测试线程状态：
     * 运行main方法，在命令行中输入jps命令，查看运行类ThreadState类的进程（pid），
     * 使用jstack pid查看类中线程状态（详见文件jstackInfo.txt）
     */
    public static void main(String[] args) {
        //TIME_WAITING状态测试
        new Thread(new TimeWaiting(), "TimeWaitingThread").start();

        //WAITING状态测试
        new Thread(new Waiting(), "WaitingThread").start();

        //BLOCKED状态测试
        new Thread(new Blocked(), "BlockedThread-1").start();
        new Thread(new Blocked(), "BlockedThread-2").start();
    }


    //该线程不断的进行睡眠
    static class TimeWaiting implements Runnable {

        @Override
        public void run() {
            while (true) {
                SleepUtils.second(100);
            }
        }
    }


    //该线程在Waiting.class实例上等待
    static class Waiting implements Runnable {
        @Override
        public void run() {
            while (true) {
                synchronized (Waiting.class) {
                    try {
                        Waiting.class.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    //该线程在Blocked.class实例上加锁后，不会释放该锁
    static class Blocked implements Runnable {

        @Override
        public void run() {
            synchronized (Blocked.class) {
                while (true) {
                    SleepUtils.second(100);
                }
            }
        }
    }
}
